package com.qf.future;

import com.utils.ExecutorUtils;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 多任务组合
 */
public class Demo04 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ThreadPoolExecutor pool = ExecutorUtils.getExcutorsPool();

        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " future1 开始执行。。");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 10;
        }, pool);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " future2 开始执行。。");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 20;
        }, pool);

        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " future3 开始执行。。");
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 30;
        }, pool);


        // 三个任务全部执行完后，获取不到任务的返回结果
//        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(future1, future2, future3);
//        System.out.println("三个任务组合完成。。");
//        Void aVoid = voidCompletableFuture.get(); // 阻塞方法，等待三个任务全部执行完成
//        System.out.println(Thread.currentThread().getName()+" 三个任务全部执行完了。。");


        // 组合三个任务，返回最先执行完成的任务结果
        CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(future1, future2, future3);
        System.out.println("组合完成");
        Object o = objectCompletableFuture.get();
        System.out.println("o:"+o);


//        System.out.println(Thread.currentThread().getName() + " sum:" +future.get());
        pool.shutdown();

    }
}
